package com.lxdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxdp.dto.Result;
import com.lxdp.dto.UserDTO;
import com.lxdp.entity.Follow;
import com.lxdp.mapper.FollowMapper;
import com.lxdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxdp.service.IUserService;
import com.lxdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hong
 * @since 2023-04-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    @Override
    public Result follow(Long id, Boolean isFollow) {
        UserDTO user = UserHolder.getUser();
        if(Boolean.TRUE.equals(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(user.getId());
            follow.setFollowUserId(id);
            save(follow);
            stringRedisTemplate.opsForSet().add("follow:"+user.getId(),follow.getFollowUserId().toString());
        }else {
            LambdaQueryWrapper<Follow> wrapper = new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, user.getId()).eq(Follow::getFollowUserId, id);
            Follow one = this.getOne(wrapper);
            this.removeById(one);
            stringRedisTemplate.opsForSet().remove("follow:"+user.getId(),one.getFollowUserId().toString());

        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        return Result.ok(lambdaQuery()
                .eq(Follow::getUserId,UserHolder.getUser().getId())
                .eq(Follow::getFollowUserId,id)
                .count() > 0);
    }

    @Override
    public Result commonFollow(Long id) {
        Long userID = UserHolder.getUser().getId();
        Set<String> common = stringRedisTemplate.opsForSet().intersect("follow:" + userID, "follow:" + id);
        if(common == null || common.isEmpty()){
            return Result.ok("无共同关注");
        }
        List<Long> userIdList = common.stream().map(Long::valueOf).collect(Collectors.toList());
        System.out.println(userIdList+ "============================");
        List<UserDTO> dtoList = userService.listByIds(userIdList).stream().map(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        return Result.ok(dtoList);

    }
}
